package com.hankol.winecellar


import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.adapter.CommonDynamicAdapter
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.toast
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.CenterLayoutManager
import com.baselibrary.view.MarginDecoration
import com.baselibrary.view.banner.Transformer
import com.baselibrary.view.banner.loader.GlideImageLoader
import com.google.android.material.appbar.AppBarLayout
import com.baselibrary.activity.BaseActivity
import com.baselibrary.bean.DynamicInfoBean
import com.hankol.newretail.AllGoodsActivity
import com.hankol.newretail.adapter.StoreGoodsAdapter
import com.hankol.newretail.bean.GoodListBean
import com.hankol.winecellar.adapter.PrivateMealNormalAdapter
import com.hankol.winecellar.adapter.WineryDetailEvaluateAdapter
import com.hankol.winecellar.adapter.WineryDetailSubCoverAdapter
import com.hankol.winecellar.adapter.WinerySeckillAdapter
import com.hankol.winecellar.bean.*
import com.hankol.winecellar.databinding.ActivityWineCellarDetailBinding
//import com.hankol.winecellar.utils.BaiduMapUtils
import com.hankol.winecellar.utils.FlexBoxUtils
import com.hankol.winecellar.utils.PopUtils
import com.hankol.winecellar.viewmodel.WineCellarViewModel
import com.hanxiang.hankol.wxapi.WXManager
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**酒窖详情
 * @author: merbng
 * @time: 2021/11/30 12:48
 * @description:
 */
@Route(path = ActivityRouter.WINE_CELLAR.WINCE_CELLAR_DETAIL)
class WineCellarDetailActivity : BaseActivity(), View.OnClickListener {
    private var selectedPosition = -1
    private lateinit var viewModel: WineCellarViewModel
    private lateinit var binding: ActivityWineCellarDetailBinding
    private var coversLooperList: ArrayList<WineryCoverBean> = arrayListOf()
    private var selectedStreamData: DynamicInfoBean.DataBeanX.DataBean? = null

    //横向缩略图
    private val horizonCoverAdapter: WineryDetailSubCoverAdapter by lazy { WineryDetailSubCoverAdapter() }

    //下酒菜
    val mealAdapter: PrivateMealNormalAdapter by lazy { PrivateMealNormalAdapter() }

    //评论
    val commentAdapter: WineryDetailEvaluateAdapter by lazy { WineryDetailEvaluateAdapter() }

    //店内好货
    val storeGoodsAdapter: StoreGoodsAdapter by lazy { StoreGoodsAdapter() }

    //限时秒杀
    val seckillAdapter by lazy { WinerySeckillAdapter() }

    val mAdapter: CommonDynamicAdapter by lazy { CommonDynamicAdapter() }

    //用于点击居中
    val centerLayoutManager = CenterLayoutManager(this);
    var mDataBean: WineryDataInfoBean? = null
    var wineryCode = ""

    //为空时  是经营者自己的酒窖，从sp中取，不为空是从其他地方进入的（别人的酒窖）
    var dealerCode = ""

    var pagNum: String = "0";

    //是否有秒杀
    var isHaveSeckill = true;

    companion object {
        //附近酒窖列表进入  默认是0
        const val FROM_TYPE_CURRENT = 0

        //线上酒窖管理-预览 进入
        const val FROM_TYPE_ADUIT = 1

        const val KEY_WINERY_DETAIL_PRIEW_BEAN = "key_winery_detail_priew_bean"
    }

    //从哪进入的详情
    var fromType = FROM_TYPE_CURRENT
    var currentClickSeckillPosition = 0
    override fun getLayoutId(): Int {
        return R.layout.activity_wine_cellar_detail
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(WineCellarViewModel::class.java)
        binding.llLoading.visibility = View.VISIBLE
        if (intent.extras.checkNotNull()) {
            //预览---
            val beanJsonStr = intent.getStringExtra(KEY_WINERY_DETAIL_PRIEW_BEAN)
            if (beanJsonStr.checkNotNull()) {//这里不能用jump的路由跳转方式，特殊符号会有问题，比如%
                val previewBean = CommonUtil.jsonToBean(beanJsonStr, WineryDetailPriewBean::class.java)
                mDataBean = previewBean2DataInfoBean(previewBean)
                SpUtils.getInstance().currentWineryInfo.let {
                    mDataBean?.wineryName = it.wineryName.checkValue()
                    mDataBean?.detailAddress = it.wineryAddress.checkValue()
                }
            }

            //查看详情
            if (ARouterUtils.parseParams(intent.extras!!, "id").isNotEmpty()) {
                if (ARouterUtils.parseParams(intent.extras!!, "id")[0].checkNotNull()) {
                    wineryCode = ARouterUtils.parseParams(intent.extras!!, "id")[0]
                }
            }
            if (ARouterUtils.parseParams(intent.extras!!, "dealerCode").isNotEmpty()) {
                if (ARouterUtils.parseParams(intent.extras!!, "dealerCode")[0].checkNotNull()) {
                    dealerCode = ARouterUtils.parseParams(intent.extras!!, "dealerCode")[0]
                }
            }
            if (ARouterUtils.parseParams(intent.extras!!, "fromType").isNotEmpty()) {
                if (ARouterUtils.parseParams(intent.extras!!, "fromType")[0].checkNotNull()) {
                    fromType = ARouterUtils.parseParams(intent.extras!!, "fromType")[0].toInt()
                }
            }
        }
        StatusBarUtil.setStatusBarHeight(binding.root, this)
        StatusBarUtil.setRootViewFitsSystemWindows(this, false)
        initView()
        initListener()
        initObserver()
        requestData()
        //获取页面开始时间
        SensorsDataManager.instance.onCreateTime()
        SensorsDataManager.instance.setWineryCommentPagePos("酒窖详情页")
        SensorsDataManager.instance.setWineryDynamicPagePos("酒窖详情页")
    }

    private fun previewBean2DataInfoBean(previewBean: WineryDetailPriewBean?): WineryDataInfoBean? {
        val wineryDataInfoBean = WineryDataInfoBean()
        previewBean?.let {
            wineryDataInfoBean.wineryImg = it.cover
            wineryDataInfoBean.winerySlideshow = CommonUtil.list2json(it.winerySlideshow)
            wineryDataInfoBean.consumptionPrice = it.consumptionPrice
            wineryDataInfoBean.startTime = it.startTime
            wineryDataInfoBean.endTime = it.endTime
            wineryDataInfoBean.wineryDealerPhone = it.wineryDealerPhone
            wineryDataInfoBean.wineryDesc = it.wineryDesc
            wineryDataInfoBean.wineryFacility = it.wineryFacility
            wineryDataInfoBean.wineryFeature = it.wineryFeature
            wineryDataInfoBean.distance = it.distance
            it.wineryFeature.split(",").forEachIndexed { index, s ->
                wineryDataInfoBean.wineryLabelConfigFeature.add(LabelConfigFacilityBean(s, index, checked = false))
            }
            it.wineryFacility.split(",").forEachIndexed { index, s ->
                wineryDataInfoBean.wineryLabelConfigFacility.add(LabelConfigFacilityBean(s, index, checked = false))
            }
        }
        return wineryDataInfoBean
    }

    private fun initView() {
        binding.includeTop.apply {
            rvCover.layoutManager = centerLayoutManager;
            rvCover.adapter = horizonCoverAdapter
        }
        centerLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        binding.rvHorizontalMeal.adapter = mealAdapter
        binding.rvComment.adapter = commentAdapter
        //限时秒杀
        binding.rvHorizontalSeckill.adapter = seckillAdapter
        binding.rvHorizontalSeckill.itemAnimator = null
        //店内好货
        binding.rvStoreGoods.adapter = storeGoodsAdapter
        binding.rvStoreGoods.layoutManager = GridLayoutManager(this, 2)
        binding.rvStoreGoods.addItemDecoration(MarginDecoration(this, 9))
        if (binding.llTab0.visibility == View.GONE && binding.llTab1.visibility == View.GONE && binding.llTab2.visibility == View.GONE && binding.llTab3.visibility == View.VISIBLE) {
            viewModel.boldShowTag(binding.tvSubTitleDynamic, binding.imgDynamicTag, true)
        }
        binding.rvCellarDynamic.adapter = mAdapter
        binding.rvCellarDynamic.addItemDecoration(MarginDecoration(this, 8))
        binding.toolbar.setBackgroundColor(Color.argb(0, 255, 255, 255))
        binding.tvUserNameTop.alpha = 0f

        binding.rvHorizontalSeckill.isNestedScrollingEnabled = false;
        binding.rvStoreGoods.isNestedScrollingEnabled = false;
        binding.rvHorizontalMeal.isNestedScrollingEnabled = false;
        binding.rvComment.isNestedScrollingEnabled = false;
        binding.rvCellarDynamic.isNestedScrollingEnabled = false;
        binding.smartRefresh.setEnableLoadMore(false);
    }

    private fun initObserver() {
        viewModel.wineryDataInfoLD.observe(this, Observer {
            if (it.checkNotNull()) {
                mDataBean = it
                SensorsDataManager.instance.setWineryName(it.wineryName.checkValue())
                //酒窖详情  顶部数据
                setDataInfo()

            } else {
                binding.llSoldOut.visibility = View.VISIBLE
            }
        })
        viewModel.supportLiveData.observe(this, Observer {
            if (it) {
                selectedStreamData?.let { bean ->
                    bean.supportNum = if (bean.isSupported) bean.supportNum.minus(1) else bean.supportNum.plus(1)
                    bean.isSupported = !bean.isSupported
                    mAdapter.notifyItemChanged(selectedPosition)
                }
            }
        })
        viewModel.dynamicStreamLD.observe(this, Observer {

            binding.smartRefresh.finishRefresh()
            if (it.checkNotNull()) {
                if (it.totalCount in 1..2) {
                    binding.viewCellarBot.visibility = View.VISIBLE
                } else {
                    binding.viewCellarBot.visibility = View.GONE
                }
                if (pagNum == "0") {
                    if (it.data.isNullOrEmpty()) {
                        binding.llTab3.visibility = View.GONE
                        binding.llScrollDynamic.visibility = View.GONE
                    } else {
                        showTab()
                        //binding.includeTop.vContentBottom.visibility = View.VISIBLE
                        binding.llTab3.visibility = View.VISIBLE
                        binding.llScrollDynamic.visibility = View.VISIBLE
                        binding.llContent.visibility = View.VISIBLE
                        mAdapter.setNewData(it.data)
                        binding.tvDynamicNum.text = "酒窖动态（${it.totalCount}）"
                        pagNum = it.nextCursor
                    }
                } else {
                    if (it.data.isNotEmpty()) {
                        mAdapter.addData(it.data)
                        pagNum = it.nextCursor
                    }
                }
            } else {
                if (pagNum == "0") {
                    binding.tvDynamicNum.visibility = View.GONE
                    binding.rvCellarDynamic.visibility = View.GONE
                }
            }
            viewModel.requestComplate()
        })
        viewModel.privateMealListLD.observe(this, Observer {

            binding.smartRefresh.finishRefresh()
            //下酒菜 列表
            mealAdapter.setNewData(it.data)
            binding.tvMealNum.text = "私房下酒菜（${it.totalCount}）"
            if (it.data.size == 0) {
                //隐藏下酒菜模块
                binding.llScrollMeal.visibility = View.GONE
                binding.llTab1.visibility = View.GONE
            } else {
                //显示下酒菜模块
                showTab()
                binding.includeTop.vContentBottom.visibility = View.VISIBLE
                binding.llTab1.visibility = View.VISIBLE
                binding.llScrollMeal.visibility = View.VISIBLE
                binding.llContent.visibility = View.VISIBLE
            }
            viewModel.requestComplate()
        })
        viewModel.evaluateListLD.observe(this, Observer {

            binding.smartRefresh.finishRefresh()
            //评价 列表  最多显示5条评论，当显示中的评论数超过5条时，显示“查看全部 XX条评价”，XX=评价总数，点击后跳转到评价列表页
            commentAdapter.setNewData(it.data)
            binding.tvCommentNum.text = "种草评价（${it.totalCount}）"
            binding.tvSeeAllComment.text = "查看全部评价（${it.totalCount}）"
            binding.tvSeeAllComment.visibility = if (it.totalCount > 5) View.VISIBLE else View.GONE
            if (it.data.size == 0) {
                //隐藏评价模块
                binding.llScrollComment.visibility = View.GONE
                binding.llTab2.visibility = View.GONE
            } else {
                //显示评价模块
                showTab()
                binding.includeTop.vContentBottom.visibility = View.VISIBLE
                binding.llTab2.visibility = View.VISIBLE
                binding.llScrollComment.visibility = View.VISIBLE
                binding.llContent.visibility = View.VISIBLE
            }
            viewModel.requestComplate()
        })
        viewModel.storeGoodsLD.observe(this, Observer {

            binding.smartRefresh.finishRefresh()
            //商品超出10个后，显示“查看全部 XX”按钮,XX=酒窖已上架商品总数，点击跳转到“全部商品页”
            storeGoodsAdapter.setNewData(it.data)
            binding.tvStoreGoodsNum.text = "店内好货（${it.totalCount}）"
            binding.tvSeeAllStoreGoods.text = "查看全部（${it.totalCount}）"
            binding.tvSeeAllStoreGoods.visibility = if (it.totalCount > 10) View.VISIBLE else View.GONE
            if (it.data.size == 0) {
                //隐藏店内好货模块
                binding.llScrollStoreGoods.visibility = View.GONE
                binding.llScrollSeckill.visibility = View.GONE
                binding.vStoreGoods.visibility = View.VISIBLE
                binding.llTab0.visibility = View.GONE
            } else {
                //显示店内好货模块
                showTab()
                binding.includeTop.vContentBottom.visibility = View.VISIBLE
                binding.llTab0.visibility = View.VISIBLE
                binding.llScrollStoreGoods.visibility = View.VISIBLE
                binding.llContent.visibility = View.VISIBLE
                binding.vStoreGoods.visibility = View.GONE
            }
            viewModel.requestComplate()
        })
        //限时秒杀
        viewModel.seckillListLD.observe(this, Observer {
            binding.smartRefresh.finishRefresh()
            //限时秒杀 列表
            seckillAdapter.setNewData(it.data)
            binding.tvSeckillNum.text = "限时秒杀（${it.totalCount}）"
            if (it.data.size == 0) {
                isHaveSeckill = false
                //隐藏限时秒杀模块
                binding.llScrollSeckill.visibility = View.GONE
            } else {
                isHaveSeckill = true
                //显示限时秒杀模块
                showTab()
                binding.includeTop.vContentBottom.visibility = View.VISIBLE
                binding.llScrollSeckill.visibility = View.VISIBLE
                binding.llContent.visibility = View.VISIBLE
            }
        })
        //店内好货、下酒菜、评论、动态 接口都加载完毕
        viewModel.reqComplateLD.observe(this, Observer {
            if (it) {
                binding.llLoading.postDelayed(Runnable {
                    //解决华为手机闪一下
                    binding.llLoading.visibility = View.GONE
                    binding.smartRefresh.visibility = View.VISIBLE
                }, 50)
                if (storeGoodsAdapter.data.size != 0) {
                    viewModel.boldShowTag(binding.tvSubTitleStoreGoods, binding.imgStoreGoodsTag, true)
                    viewModel.boldShowTag(binding.tvSubTitleMeal, binding.imgMealTag, false)
                    viewModel.boldShowTag(binding.tvSubTitleComment, binding.imgCommentTag, false)
                    viewModel.boldShowTag(binding.tvSubTitleDynamic, binding.imgDynamicTag, false)
                } else if (storeGoodsAdapter.data.size == 0 && mealAdapter.data.size != 0) {
                    viewModel.boldShowTag(binding.tvSubTitleStoreGoods, binding.imgStoreGoodsTag, false)
                    viewModel.boldShowTag(binding.tvSubTitleMeal, binding.imgMealTag, true)
                    viewModel.boldShowTag(binding.tvSubTitleComment, binding.imgCommentTag, false)
                    viewModel.boldShowTag(binding.tvSubTitleDynamic, binding.imgDynamicTag, false)
                } else if (mealAdapter.data.size == 0 && commentAdapter.data.size != 0) {
                    viewModel.boldShowTag(binding.tvSubTitleStoreGoods, binding.imgStoreGoodsTag, false)
                    viewModel.boldShowTag(binding.tvSubTitleMeal, binding.imgMealTag, false)
                    viewModel.boldShowTag(binding.tvSubTitleComment, binding.imgCommentTag, true)
                    viewModel.boldShowTag(binding.tvSubTitleDynamic, binding.imgDynamicTag, false)
                } else if (mealAdapter.data.size == 0 && commentAdapter.data.size == 0) {
                    binding.rvCellarDynamic.postDelayed(Runnable {
                        if (mAdapter.data.size != 0) {
                            viewModel.boldShowTag(binding.tvSubTitleStoreGoods, binding.imgStoreGoodsTag, false)
                            viewModel.boldShowTag(binding.tvSubTitleMeal, binding.imgMealTag, false)
                            viewModel.boldShowTag(binding.tvSubTitleComment, binding.imgCommentTag, false)
                            viewModel.boldShowTag(binding.tvSubTitleDynamic, binding.imgDynamicTag, true)
                        }
                    }, 100)
                }
                if (storeGoodsAdapter.data.size.plus(mealAdapter.data.size).plus(commentAdapter.data.size).plus(mAdapter.data.size) == 0) {
                    val mAppBarChildAt: View = binding.ablTop.getChildAt(0)
                    val mAppBarParams = mAppBarChildAt.layoutParams as AppBarLayout.LayoutParams
                    mAppBarParams.scrollFlags = 0
                } else if (storeGoodsAdapter.data.size.plus(
                        commentAdapter.data.size
                    ).plus(
                        mAdapter.data.size
                    ) == 0 && mealAdapter.data.size != 0
                ) {//如果只有下酒菜，则显示占位，避免 划不动
                    binding.vMealHolder.visibility = View.VISIBLE
                }
            }
        })

        //秒杀--取消预约
        viewModel.seckillCancelSubLD.observe(this, Observer {
            //取消预约成功
            seckillAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeFlg = 0
            seckillAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeNum = seckillAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeNum?.minus(1)!!
            seckillAdapter.notifyItemChanged(currentClickSeckillPosition)
            "取消提醒成功".toast()
        })
        //秒杀--添加预约
        viewModel.seckillAddSubLD.observe(this, Observer {
            com.baselibrary.utils.PopUtils.showSeckillInternetSuccessDialog(this, TimeUtil.setYearMonthDay(it.stime), "${it.subscribeRemind}")
            seckillAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeFlg = 1
            seckillAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeNum = seckillAdapter.data[currentClickSeckillPosition].seckillActProductExtDTO?.subscribeNum?.plus(1)!!
            seckillAdapter.notifyItemChanged(currentClickSeckillPosition)
        })
    }

    private fun setDataInfo() {
        mDataBean?.let { it ->
            binding.tvUserNameTop.text = it.wineryName.checkValue()
            var urls = mutableListOf<WineryCoverBean>()
            if (it.winerySlideshow.checkNotNull()) {
                urls = CommonUtil.jsonToList(it.winerySlideshow.checkValue(), WineryCoverBean::class.java)
            }
            binding.includeTop.apply {
                tvWineryName.text = it.wineryName.checkValue()
                tvPictureDetIndex.text = "${1}/${urls.size}"
                tvConsumptionPrice.text = "¥${it.consumptionPrice}/人"
                //简介
                tvDesc.setContent(it.wineryDesc.checkValue())
                //标签
                flLabel.removeAllViews()
                //营业时间：10:00-23:00
                tvTime.text = "营业时间：${it.startTime}-${it.endTime}"
                tvAddressName.text = it.detailAddress.checkValue()
                tvDistance.text = if (it.distance == 0) "" else "距您${CommonUtil.formatDistance(it.distance)}"
                imgCall.setOnClickListener(this@WineCellarDetailActivity)
                imgNavigation.setOnClickListener(this@WineCellarDetailActivity)
            }
            coversLooperList.clear()
            coversLooperList.addAll(urls)
            binding.includeTop.bannerCellarPicture.setImages(viewModel.createBanner(coversLooperList)).setImageLoader(GlideImageLoader(1)).setBannerAnimation(Transformer.Default).isAutoPlay(false).start()
            //横向滑动图片
            if (coversLooperList.size > 0) {
                coversLooperList[0].isSelect = true
            }
            horizonCoverAdapter.setNewData(coversLooperList)
            if (it.wineryLabelConfigFeature.checkNotNull()) {
                it.wineryLabelConfigFeature.forEachIndexed { index, labelConfigFacilityBean ->
                    if (index < 3) {
                        FlexBoxUtils.addChildToFlexboxLayout(binding.includeTop.flLabel, labelConfigFacilityBean)
                    }
                }
            } else {//预览
                val tagList = mutableListOf<LabelConfigFacilityBean>()
                it.wineryFeature.split(",").forEachIndexed { index, s ->
                    if (index < 3) {
                        if (s.checkNotNull()) {
                            tagList.add(LabelConfigFacilityBean(s, index, checked = false))
                        }
                    }
                }
                binding.includeTop.rlLabelMore.visibility = if (tagList.size > 0) View.VISIBLE else View.GONE
                for (feaBean in tagList) {
                    FlexBoxUtils.addChildToFlexboxLayout(binding.includeTop.flLabel, feaBean)
                }
            }
            //预览的时候也需要显示 评论，下酒菜，动态
            viewModel.reqSeckillList(mDataBean!!.shopId, 1)
            viewModel.reqStoreGoodsList(it.shopId, 1)
            viewModel.reqPrivateMealList(if (fromType == FROM_TYPE_CURRENT) wineryCode else SpUtils.getInstance().currentWineryInfo.wineryCode, 1, 20)
            viewModel.requestEvaluateList(if (fromType == FROM_TYPE_CURRENT) wineryCode else SpUtils.getInstance().currentWineryInfo.wineryCode, 1, 5)
            //酒窖动态
            viewModel.requestUserTimeline(pagNum, "${it.uid}")
        }
    }

    private fun requestData() {
        if (wineryCode.checkNotNull()) {//非预览  酒窖详情
            binding.smartRefresh.setEnableRefresh(true)
            viewModel.reqgetWineryDataInfo(fromType, wineryCode, dealerCode)
        } else {
            //预览
            //酒窖详情  顶部数据
            setDataInfo()
            binding.smartRefresh.setEnableRefresh(false)
            binding.llLoading.postDelayed(Runnable { binding.llLoading.visibility = View.GONE }, 500)
        }

    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n") private fun initListener() {
        binding.smartRefresh.setOnRefreshListener {
            pagNum = "0"
            requestData()
        }

        mAdapter.setCallback(object : CommonDynamicAdapter.Callback {
            override fun onClickLike(position: Int, item: DynamicInfoBean.DataBeanX.DataBean) {
                selectedStreamData = item
                selectedPosition = position
                viewModel.reqSupport(!item.isSupported, 4, item.id)
            }
        })
        binding.backImageView.setOnClickListener(this)
        binding.rlUserInfoBackHide.setOnClickListener(this)
        binding.imgShareHide.setOnClickListener(this)
        binding.llTab0.setOnClickListener(this)
        binding.llTab1.setOnClickListener(this)
        binding.llTab2.setOnClickListener(this)
        binding.llTab3.setOnClickListener(this)
        binding.tvSeeAllStoreGoods.setOnClickListener(this)
        binding.tvStoreGoodsNum.setOnClickListener(this)
        binding.tvSeeAllComment.setOnClickListener(this)
        binding.tvCommentNum.setOnClickListener(this)
        binding.tvDynamicNum.setOnClickListener(this)
        binding.tvSeckillNum.setOnClickListener(this)
        binding.includeTop.rlLabelMore.setOnClickListener(this)
        binding.includeTop.bannerCellarPicture.setOnBannerListener {
            elementClick("详情大图")
            viewModel.seeBigImg(viewModel.createBigIMg(coversLooperList), it, emptyList(), emptyList())
        }.setOnBannerCurrentShowListener { //图片 or 视频
            binding.includeTop.imgVideoTag.visibility = if (coversLooperList[it].type == 0) View.GONE else View.VISIBLE

            horizonCoverAdapter.upSelected(it)//更新小图选中状态
            binding.includeTop.tvPictureDetIndex.text = "${it + 1}/${coversLooperList.size}"
            centerLayoutManager.smoothScrollToPosition(binding.includeTop.rvCover, RecyclerView.State(), it)
        }


        binding.ablTop.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            val offset = ScreenUtils.dpToPx(81)
            if (-verticalOffset in 0..offset) {
                binding.tvUserNameTop.alpha = (verticalOffset / offset).toFloat()
                binding.toolbar.setBackgroundColor(Color.argb((255 * (verticalOffset / offset)).toInt(), 255, 255, 255))
                binding.tvUserNameTop.setTextColor(Color.argb((255 * (verticalOffset / offset)).toInt(), 255, 255, 255))
            } else {
                binding.tvUserNameTop.alpha = 1f
                binding.toolbar.setBackgroundColor(Color.argb(255, 255, 255, 255))
                binding.tvUserNameTop.setTextColor(Color.argb(255, 0, 0, 0))
                StatusBarUtil.setStatusBarDarkTheme(this, true)
            }
        })
        binding.csvScroll.setOnScrollChangeListener { v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int ->
            viewModel.upSubTitle(this, scrollY, binding)
        }

        horizonCoverAdapter.setOnItemClickListener { _, _, position ->
            elementClick("详情小图")
            if (coversLooperList[position].isSelect) {
                //进入大图
                viewModel.seeBigImg(viewModel.createBigIMg(coversLooperList), position, emptyList(), emptyList())
                return@setOnItemClickListener
            }

            horizonCoverAdapter.upSelected(position)
            binding.includeTop.bannerCellarPicture.setCurrentItem(position)
            centerLayoutManager.smoothScrollToPosition(binding.includeTop.rvCover, RecyclerView.State(), position)
        }
        mealAdapter.setOnItemClickListener { adapter, view, position ->
            //下酒菜点击
            //图片详情
            val listBean = adapter.data as List<PrivateMealManageListBean>
            val coverUrlList = mutableListOf<String>()
            val nameStrList = mutableListOf<String>()
            val descStrList = mutableListOf<String>()
            for (bean in listBean) {
                val wineryCoverBean = CommonUtil.jsonToBean(bean.appetizerImg.checkValue(), WineryCoverBean::class.java)
                coverUrlList.add(if (wineryCoverBean.type == 0) wineryCoverBean.coverUrl.checkValue() else wineryCoverBean.videoUrl.checkValue())
                nameStrList.add("${bean.appetizerName}")
                descStrList.add("${bean.appetizerDesc}")
            }
            viewModel.seeBigImg(coverUrlList, position, nameStrList, descStrList)
            cellarFoodSee(nameStrList[position].checkValue())
        }
        //店内好货--商品详情
        storeGoodsAdapter.setOnItemClickListener { adapter, view, position ->
            //进入商品详情
            val map = HashMap<String, Any>()
            map[Constants.GOODS_DETAIL_ID] = (adapter.data[position] as GoodListBean).id
            map[Constants.GOODS_DETAIL_SOURCE] = "酒窖详情页"
            ARouterUtils.jump(ActivityRouter.NEW_RETAIL.GOODS_DETAUILS, map)
        }
        seckillAdapter.setOnItemClickListener { _, _, position ->
            val seckillBean = seckillAdapter.data[position]
            if (!DoubleClickHelper.isOnDoubleClick()) {
                val map = java.util.HashMap<String, Any>()
                map[Constants.GOODS_DETAIL_ID] = seckillBean.spuId
                map[Constants.GOODS_SKU_ID] = "${seckillBean.seckillActProductExtDTO?.skuId}"
                map[Constants.GOODS_DETAIL_SOURCE] = "酒窖详情页"
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.GOODS_DETAUILS, map)
            }
        }
        seckillAdapter.setOnItemChildClickListener { _, v, position ->
            currentClickSeckillPosition = position
            if (!DoubleClickHelper.isOnDoubleClick()) {
                val seckillBean = seckillAdapter.data[position];
                when (v.id) {
                    R.id.tv_option -> {
                        seckillBean.seckillActProductExtDTO?.let {
                            if (TimeUtil.getCurrentTimeMillis().minus(seckillBean.stime) > 0) {
                                //进行中 & 已抢光
                                val isOver = it.sales >= it.stock
                                if (isOver) {
                                    //已抢光
                                } else {
                                    //抢购
                                    val map = java.util.HashMap<String, Any>()
                                    map[Constants.GOODS_DETAIL_ID] = seckillBean.spuId
                                    map[Constants.GOODS_SKU_ID] = it.skuId
                                    map[Constants.GOODS_DETAIL_SOURCE] = "酒窖详情页"
                                    ARouterUtils.jump(ActivityRouter.NEW_RETAIL.GOODS_DETAUILS, map)
                                }
                            } else {
                                //未开始  //是否预约:0未预约，1已预约
                                if (it.subscribeFlg == 1) {
                                    //已预约 --> 取消预约
                                    viewModel.reqSeckillCancelSubscribe("${it.seckillActId}")
                                } else {
                                    //未预约，  添加预约
                                    viewModel.reqSeckillAddSubscribe("${it.seckillActId}")
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.backImageView, R.id.rl_userInfo_back_hide -> {
                finish()
            }
            R.id.ll_tab_0 -> {//店内好货
                binding.ablTop.setExpanded(false)//折叠appBar
                binding.csvScroll.scrollTo(0, if (isHaveSeckill) binding.llScrollSeckill.top else binding.llScrollStoreGoods.top)
                viewModel.boldShowTag(binding.tvSubTitleStoreGoods, binding.imgStoreGoodsTag, true)
                viewModel.boldShowTag(binding.tvSubTitleMeal, binding.imgMealTag, false)
                viewModel.boldShowTag(binding.tvSubTitleComment, binding.imgCommentTag, false)
                viewModel.boldShowTag(binding.tvSubTitleDynamic, binding.imgDynamicTag, false)
            }
            R.id.ll_tab_1 -> {//下酒菜
                binding.ablTop.setExpanded(false)//折叠appBar
                binding.csvScroll.scrollTo(if (isHaveSeckill) binding.llScrollSeckill.top else binding.llScrollStoreGoods.top, binding.llScrollMeal.top)
                viewModel.boldShowTag(binding.tvSubTitleStoreGoods, binding.imgStoreGoodsTag, false)
                viewModel.boldShowTag(binding.tvSubTitleMeal, binding.imgMealTag, true)
                viewModel.boldShowTag(binding.tvSubTitleComment, binding.imgCommentTag, false)
                viewModel.boldShowTag(binding.tvSubTitleDynamic, binding.imgDynamicTag, false)
            }
            R.id.ll_tab_2 -> {//评价
                binding.ablTop.setExpanded(false)//折叠appBar
                binding.csvScroll.scrollTo(binding.llScrollMeal.top, binding.llScrollComment.top)
                viewModel.boldShowTag(binding.tvSubTitleStoreGoods, binding.imgStoreGoodsTag, false)
                viewModel.boldShowTag(binding.tvSubTitleMeal, binding.imgMealTag, false)
                viewModel.boldShowTag(binding.tvSubTitleComment, binding.imgCommentTag, true)
                viewModel.boldShowTag(binding.tvSubTitleDynamic, binding.imgDynamicTag, false)
            }
            R.id.ll_tab_3 -> {//动态
                binding.ablTop.setExpanded(false)//折叠appBar
                binding.csvScroll.scrollTo(0, binding.llScrollDynamic.top)
                viewModel.boldShowTag(binding.tvSubTitleStoreGoods, binding.imgStoreGoodsTag, false)
                viewModel.boldShowTag(binding.tvSubTitleMeal, binding.imgMealTag, false)
                viewModel.boldShowTag(binding.tvSubTitleComment, binding.imgCommentTag, false)
                viewModel.boldShowTag(binding.tvSubTitleDynamic, binding.imgDynamicTag, true)
            }
            R.id.tv_see_all_store_goods, R.id.tv_store_goods_num -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    mDataBean?.let {
                        //查看全部
                        val hashMap = HashMap<String, Any>()
                        hashMap[AllGoodsActivity.KEY_SHOP_ID] = it.shopId
                        ARouterUtils.jump(ActivityRouter.NEW_RETAIL.ALL_GOODS, hashMap)
                    }
                }
            }
            R.id.tv_see_all_comment, R.id.tv_comment_num -> {
                SensorsDataManager.instance.setWineryCommentPagePos("全部评价页")
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    //查看全部评价
                    val hashMap = HashMap<String, Any>()
                    hashMap["wineryCode"] = wineryCode
                    ARouterUtils.jump(ActivityRouter.WINE_CELLAR.ALL_EVALUATE, hashMap)
                }
            }
            R.id.rl_label_more -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    //酒窖服务弹窗
                    mDataBean?.let {
                        PopUtils.showWinecellarServiceDialog(this, it)
                    }
                }
            }
            R.id.img_call -> {
                elementClick("电话")
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    //打电话
                    PermissionsUtils.getInstance().chekPermissions(this, PermissionCollection.CALL_PHONE.getPermissionList(), object : PermissionsCall() {
                        override fun permissionsPass() {
                            CommonUtil.callPhone(this@WineCellarDetailActivity, mDataBean?.wineryDealerPhone)
                        }
                    })
                }
            }
            R.id.img_navigation -> {
                elementClick("导航")
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    //导航
                    val currentLatitude = SpUtils.getFloat(ContextUtils.getCurApplication().applicationContext, "address_Lat", 0f)
                    val currentLongitude = SpUtils.getFloat(ContextUtils.getCurApplication().applicationContext, "address_long", 0f)
//                    BaiduMapUtils.initNav(this@WineCellarDetailActivity, currentLongitude.toDouble(), currentLatitude.toDouble(), "当前位置", mDataBean?.longitude!!.toDouble(), mDataBean?.latitude!!.toDouble(), mDataBean?.wineryName.checkValue())
                }
            }
            R.id.img_share_hide-> {
                elementClick("分享")
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    shareOption()

                }
            }
            R.id.tv_dynamic_num -> {
                //查看全部动态
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    val hashMap = HashMap<String, Any>()
                    hashMap["uid"] = "${mDataBean?.uid}"
                    ARouterUtils.jump(ActivityRouter.WINE_CELLAR.WINCE_ALL_DYNAMIC, hashMap)
                }
            }
            R.id.tv_seckill_num -> {
                //酒窖全部秒杀
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    SensorsDataManager.instance.cellarSeckillPageView()
                    val hashMap = HashMap<String, Any>()
                    hashMap["shopId"] = "${mDataBean?.shopId}"
                    ARouterUtils.jump(ActivityRouter.WINE_CELLAR.WINCE_ALL_SECKILL, hashMap)
                }
            }
        }
    }

    private fun shareOption() {
        if (mDataBean?.shareWxAppQrImgUrl.checkNotNull()) {
            //分享 弹窗
            com.baselibrary.utils.PopUtils.showBottomSharePosterExe(this, object : com.baselibrary.utils.PopUtils.IBottomShareWxExePosterCallBack {
                override fun clickWxExe() {
                    mDataBean?.let {
                        //分享小程序
                        WXManager.shareToWxExe(this@WineCellarDetailActivity, Config.MINI_PROGRAM_ID, "${Config.MINI_PROGRAM_PAGE_PATH_WINERY_DETAIL}${it?.shopId}", "${it?.wineryName.checkValue()}", it?.wineryName.checkValue(), "${AppUtils.getSaveShareHostUrl()}/html/share/shareApp.html", it?.wineryImg.checkValue())
                    }
                }

                override fun clickPoster() {
                    //分享
                    mDataBean?.let {
                        if (it.winerySlideshow.checkNotNull()) {
                            PermissionsUtils.getInstance().chekPermissions(this@WineCellarDetailActivity, PermissionCollection.FILE.permissionList, object : PermissionsCall() {
                                override fun permissionsPass() {
                                    val bundle = Bundle()
                                    bundle.putParcelable(WineCellarPosterActivity.KEY_WINERY_DATA_INFO, wineryInfoDataBean2WineCellarPosterParams())
                                    ActivityRouter.startActivity(ActivityRouter.WINE_CELLAR.SHARE_POSTER, bundle)
                                }
                            })
                        }
                    }
                }
            })
        } else {
            //小程序未上线，直接进海报
            mDataBean?.let {
                if (it.winerySlideshow.checkNotNull()) {
                    PermissionsUtils.getInstance().chekPermissions(this@WineCellarDetailActivity, PermissionCollection.FILE.permissionList, object : PermissionsCall() {
                        override fun permissionsPass() {
                            val bundle = Bundle()
                            bundle.putParcelable(WineCellarPosterActivity.KEY_WINERY_DATA_INFO, wineryInfoDataBean2WineCellarPosterParams())
                            ActivityRouter.startActivity(ActivityRouter.WINE_CELLAR.SHARE_POSTER, bundle)
                        }
                    })
                }
            }
        }
    }

    fun wineryInfoDataBean2WineCellarPosterParams(): WineCellarPosterParams? {
        return mDataBean?.wineryLabelConfigFeature?.let {
            WineCellarPosterParams(bgCover = mDataBean?.wineryImg.checkValue(), qrCode = if (mDataBean?.shareWxAppQrImgUrl.checkNotNull()) mDataBean?.shareWxAppQrImgUrl.checkValue() else Config.DOWNLOAD_THE_LANDING_PAGE_URL, title = mDataBean?.wineryName.checkValue(), price = "${mDataBean?.consumptionPrice}", address = "${mDataBean?.provinceName.checkValue()}${if (mDataBean?.cityName.checkValue().equals(mDataBean?.provinceName.checkValue())) "" else mDataBean?.cityName.checkValue()}${mDataBean?.detailAddress.checkValue()}", label = it.map { it.labelName })
        }
    }

    //详情大图、详情小图、导航、电话、分享
    fun elementClick(elementName: String) {
        SensorsDataManager.instance.cellarDetailsElement(mDataBean?.wineryName.checkValue(), elementName)
    }

    //点击私房下酒菜图片/视频 时触发
    fun cellarFoodSee(foodName: String) {
        SensorsDataManager.instance.cellarFoodSee(mDataBean?.wineryName.checkValue(), foodName)
    }

    @SuppressLint("SetTextI18n") @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_change_dynamic_like_status) {
            for ((index, data) in mAdapter.data.withIndex()) {
                if (data.id == messageBus.param1) {
                    data.isSupported = !data.isSupported
                    data.supportNum = if (data.isSupported) data.supportNum.plus(1) else data.supportNum.minus(1)
                    mAdapter.notifyItemChanged(index)
                    break
                }
            }
        } else if (messageBus.codeType == MessageBus.msgId_refresh_seckill_sub_status) {
            mDataBean?.let {
                viewModel.reqSeckillList(it.shopId, 1)
            }
        } else if (messageBus.codeType == MessageBus.msgId_seckill_once_end) {
            //只有一个秒杀商品 结束时， 刷新
            viewModel.reqSeckillList(mDataBean!!.shopId, 1)
        }
    }

    fun showTab() {
        binding.llTab.visibility = View.VISIBLE
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
        //获取页面结束时间
        SensorsDataManager.instance.onDestroyTime()
        if (SensorsDataManager.instance.getBrowseTime() != 0L) {
            SensorsDataManager.instance.cellarDetailsBrowse(mDataBean?.wineryName.checkValue())
        }
    }
}